package com.ngc.mall.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ngc.mall.common.configure.mybatisPlus.BaseServiceImpl;
import com.ngc.mall.domain.AdminRoleDomain;
import com.ngc.mall.dto.RoleDTO;
import com.ngc.mall.mapper.RoleMapper;
import com.ngc.mall.service.IRoleMenuService;
import com.ngc.mall.service.IRoleService;
import com.ngc.mall.vo.RoleVO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class RoleServiceImpl extends BaseServiceImpl<RoleMapper, AdminRoleDomain> implements IRoleService {

    @Resource
    private IRoleMenuService iRoleMenuService;

    @Override
    public List<RoleVO> selectAllRole() {
        List<RoleVO> adminRoleList = new ArrayList<>();
//        return super.list(Wrappers.<AdminRoleDomain>lambdaQuery().orderByDesc(AdminRoleDomain::getCreateTime));
        List<AdminRoleDomain> adminRoleDomainList = super.list();
        for (AdminRoleDomain domain : adminRoleDomainList) {
            List<Long> menuList = iRoleMenuService.findMenuByRoleId(domain.getId());
            RoleVO vo = RoleVO.builder()
                    .id(domain.getId())
                    .name(domain.getName())
                    .note(domain.getNote())
                    .permissions(menuList)
                    .isEnabled(domain.getIsEnabled())
                    .createTime(domain.getCreateTime())
                    .build();
            adminRoleList.add(vo);
        }
        return adminRoleList;

    }

    @Override
    @Transactional
    public Boolean createRole(RoleDTO dto) {
        Long id = super.create(AdminRoleDomain.builder().note(dto.getNote()).name(dto.getName()).isEnabled(dto.getIsEnabled()).build());
        if (dto.getPermissions().isEmpty()) {
            return true;
        }
        return baseMapper.insertMenuByRoleId(dto.getPermissions(), id);
    }

    @Override
    @Transactional
    public Boolean updateRoleById(Long id, RoleDTO dto) {
        super.update(Wrappers.<AdminRoleDomain>lambdaUpdate()
                .eq(AdminRoleDomain::getId, id)
                .set(AdminRoleDomain::getName, dto.getName())
                .set(AdminRoleDomain::getNote, dto.getNote())
                .set(AdminRoleDomain::getIsEnabled, dto.getIsEnabled())
        );
        baseMapper.removeMenuByRoleId(id);
        if (dto.getPermissions().isEmpty()) {
            return true;
        }
        return baseMapper.insertMenuByRoleId(dto.getPermissions(), id);
    }

    @Override
    public AdminRoleDomain getDetailById(Long id) {
        AdminRoleDomain domain = super.check(id);
        domain.setPermissions(baseMapper.getMenuByRoleId(id));
        return domain;

    }

}
